import { __private } from "cc";

/**
 * 状态盒
 * 状态模式的实现
 * 这既是状态机本身，也是状态，以实现层次状态机
 */
export class StateBlock{
    private states : Map<string,StateBlock> = new Map();

    public currentStateKey : string = "";

    public get currentState() : StateBlock
    {
        return this.states.get(this.currentStateKey);
    }

    private active : boolean = false;

    /**
     * 作为状态类时，获取父状态盒
     */
    public parent : StateBlock = null;

    /**
     * 状态盒初始状态
     */
    protected InitState : typeof StateBlock = null

    public get Active() : boolean {
        return this.active;
    }
    
    public Start(){
        if(!this.active){
            this.active = true;

            if(!this.InitState){
                console.error("StateBlock: 未设置初始状态！");
            }else{
                this.changeState(this.InitState);
            }
        }
    }

    public Close(){
        let state = this.states.get(this.currentStateKey);
        if(state){
            state.Close();
            state.onExit();
        }
        this.active = false;
    }

    /**
     * 作为状态机，改变当前状态
     * @param type StateBlock的构造方法
     */
    public changeState<T extends StateBlock>(type : new()=> T){
        if(!this.active)
        {
            console.error("StateBlock: 状态机未启动！")
            return;
        }
        let state = this.states.get(type.name);
        //  若states里没有，新建一个
        if(!state){
            state = new type();
            state.parent = this;
            this.states.set(type.name,state);
        }
        
        //  获取旧状态并调用其onExit
        let currentState = this.states.get(this.currentStateKey);
        if(currentState){
            currentState.onExit();
        }
        this.currentStateKey = type.name;
        currentState = this.states.get(this.currentStateKey);
        currentState.onEnter();
    }

    /**
     * 进入状态时调用
     * 
     */
    public onEnter(){

    }

    /**
     * 退出状态时调用
     */
    public onExit(){
        
    }

}